package com.franklin.ideaplugin.api.collection.map;

import com.google.common.collect.Maps;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 递归算法缓存map
 * 例如计算斐波那契数列
 *
 * @author Ye Junhui
 * @since 2023/9/25
 */
public class RecursionMap<K,V> extends LinkedHashMap<K,V> {

    private final Map<Object,Integer> accessTimeMap = Maps.newHashMap();

    @Override
    public boolean containsKey(Object key) {
        if (getTime(key) == 1){
            add(key);
            return super.containsKey(key);
        }
        add(key);
        return true;
    }

    private void add(Object key){
        Integer time = accessTimeMap.getOrDefault(key, 1);
        accessTimeMap.put(key,time + 1);
    }

    private Integer getTime(Object key){
        Integer time = accessTimeMap.getOrDefault(key, 1);
        accessTimeMap.putIfAbsent(key,time);
        return time;
    }
}
